package com.white.commonlib.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import com.white.commonlib.manager.ThreadManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;

/**
 * 网络工具类
 */
public class NetUtil
{

    /***
     * 判断网络是否可用
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context)
    {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        } else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /***
     * 判断网络是否畅通, 同步方式
     * @return
     */
//    public static boolean isNetworkUnobstructed()
//    {
//        ExecutorService e = ThreadManager.getInstance().get();
//        Future<Integer> fu = e.submit(new Callable<Integer>()
//        {
//            @Override
//            public Integer call() throws Exception
//            {
//                //ping百度看能否返回， ping一次，超时时间为3秒
//                Process p = Runtime.getRuntime().exec("ping -c 1 -w 3 www.baidu.com");
//                return p.waitFor();
//            }
//        });
//        try
//        {
//            return fu.get() == 0;
//        } catch (InterruptedException e1)
//        {
//            e1.printStackTrace();
//            return false;
//        } catch (ExecutionException e1)
//        {
//            e1.printStackTrace();
//            return false;
//        }
//    }

    /***
     * 判断网络是否畅通, 异步方式
     * @return
     */
    public static void isNetworkUnobstructed(final ResultCallback callback)
    {
        ExecutorService e = ThreadManager.getInstance().get();
        e.submit(new Runnable()
        {
            @Override
            public void run()
            {
                Process p = null;
                try
                {
                    p = Runtime.getRuntime().exec("ping -c 1 -w 3 www.baidu.com");
                    int status = p.waitFor();
                    callback.result(status == 0);
                } catch (IOException e1)
                {
                    e1.printStackTrace();
                    callback.result(false);
                } catch (InterruptedException e1)
                {
                    e1.printStackTrace();
                    callback.result(false);
                }
            }
        });
    }

    public interface ResultCallback
    {
        void result(boolean b);
    }

    /***
     * ping任务
     * @param str  ip或域名
     */
//    public void runPingIPprocess(final String str)
//    {
//
//        final Runnable pingThread = new Runnable()
//        {
//            @Override
//            public void run()
//            {
//                try
//                {
//                    Process p = Runtime.getRuntime().exec("ping -c 1 -w 5 " + str);
//                    int status = p.waitFor();
//                    if (status == 0)
//                    {
////                        mUpdaHandler.sendEmptyMessage(0);
//                    }
//                } catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//            }
//        };
//    }


    /***
     * 获取当前网络类型
     * @param context
     * @return 2G, 3G, 4G, 如果是wifi，则返回WIFI WIFI信号强度[value]
     */
    public static String GetNetworkType(Context context)
    {
        String strNetworkType = "未连接";

        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            {
                strNetworkType = "WIFI";
//                WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//                if (manager != null)
//                {
//                    WifiInfo info = manager.getConnectionInfo();
//                    int rssi = info.getRssi();
//                    strNetworkType += "\u3000WIFI信号强度：[" + (100 - Math.abs(rssi)) + "]";
//                }
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                String _strSubTypeName = networkInfo.getSubtypeName();

                int networkType = networkInfo.getSubtype();
                switch (networkType)
                {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            strNetworkType = "3G";
                        } else
                        {
                            strNetworkType = _strSubTypeName;
                        }
                        break;
                }
            }
        }
        return strNetworkType;
    }
}


